package com.cn.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cn.pojo.TypeInfo;
import com.cn.service.TypeService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class TypeController {
	@Autowired
	@Qualifier("typeService")
	TypeService typeService;
	
	@RequestMapping(value="/addType.do")
	public ModelAndView addType(ModelAndView mv,HttpServletRequest request, String type) {
		String path=request.getServletContext().getRealPath("/upload/");
		File f=new File(path,type);
		if(!f.exists())
		{
			f.mkdirs();
		}
		typeService.addType(type, "upload\\"+type);
		mv.setViewName("consultTypeForm");
		return mv;
	}
	@RequestMapping(value="/consultType")
	public void consultType(ObjectMapper mapper,HttpServletResponse resp) {
		List<TypeInfo> typeInfo=typeService.findAll();
		try {
			String jsonfromList = mapper.writeValueAsString(typeInfo);
			resp.setCharacterEncoding("UTF-8");
			resp.setHeader("Access-Control-Allow-Origin", "*");
			try {
				resp.getWriter().print(jsonfromList);
				resp.getWriter().flush();
				resp.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/deleteType.do")
	public ModelAndView deleteType(ModelAndView mv,Integer id,HttpServletRequest request) {
		TypeInfo type=typeService.selectById(id);
		File f=new File(request.getServletContext().getRealPath("/")+type.getUrl());
		if(f.exists()) {
			f.delete();
		}
		boolean deleteType=typeService.deleteType(id);
		mv.setViewName("consultTypeForm");
		return mv;
	}
}
